package gefmvc;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import parser.AnalysisAndSearch;
import parser.SearchForNesting;

public class Model {
	private List<NodeModel> nodes;


	public Model(String PATH) {

		try {
			File input = new File(PATH);
			nodes = new ArrayList<NodeModel>();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser saxParse = factory.newSAXParser();
			AnalysisAndSearch search = new AnalysisAndSearch();
			SearchForNesting searchForNeting = new SearchForNesting();
			saxParse.parse(input, searchForNeting);
			int maxNesting = searchForNeting.getMaxNesting();
			search.setMaxNesting(maxNesting);
			saxParse.parse(input, search);

			nodes = search.getNodes();

			for (int i = 0; i < nodes.size() - 1; i++) {
				if ((nodes.get(i).getNext1() != 0)
						&& ((nodes.get(i).getNext2() == 0))) {
					NodeConnectionModel connection = new NodeConnectionModel();
					((NodeModel) (nodes.get(i)))
							.addSourceConnection(connection);
					((NodeModel) (nodes.get(nodes.get(i).getNext1())))
							.addTargetConnection(connection);
				}
				if ((nodes.get(i).getNext1() != 0)
						&& (nodes.get(i).getNext2() != 0)) {
					NodeConnectionModel connection1 = new NodeConnectionModel();
					NodeConnectionModel connection2 = new NodeConnectionModel();
					((NodeModel) (nodes.get(i)))
							.addSourceConnection(connection1);
					((NodeModel) (nodes.get(nodes.get(i).getNext1())))
							.addTargetConnection(connection1);
					((NodeModel) (nodes.get(i)))
					.addSourceConnection(connection2);
					((NodeModel) (nodes.get(nodes.get(i).getNext2())))
					.addTargetConnection(connection2);
				}
			
			}

		} catch (Exception ex) {
			System.out.println(ex.toString());
			ex.printStackTrace();
		}

	}

	public List<NodeModel> getNodes() {
		return nodes;
	}
}